using System;
using System.Reflection;
using System.Web;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Context;
using NHibernate.Driver;
using NHibernate.Mapping.ByCode;
using TelerikMvcGridCustomBindingHelper.NHibernate;

namespace ExampleWebApplication.Infraestruture.NHibernate
{
    [Serializable]
    public static class NHibernateHelper
    {
        private static readonly ISessionFactory SessionFactory;
        private const string CurrentSessionKey = "nhibernate.current_session";

        static NHibernateHelper()
        {
            if (SessionFactory != null)
                return;

            var nhCfg = new Configuration();
            nhCfg.DataBaseIntegration(db =>
               {
                   //db.ConnectionString = "Data Source=|DataDirectory|Northwind.sl3;Version=3;Read Only=True;FailIfMissing=True;";
                   //db.Driver<SQLite20Driver>();
                   //db.Dialect<SQLiteDialect>();
                   db.ConnectionStringName = "NorthwindConnectionString";
                   db.Driver<SqlClientDriver>();
                   // NHibernate has a bug when using "use_sql_comments=true"
                   db.Dialect<MsSql2008DialectBugFix>();
                   // Debuging
                   db.LogSqlInConsole = true;
                   db.LogFormattedSql = true;
                   db.AutoCommentSql = true;
               }).SessionFactory().GenerateStatistics();

            var mapper = new ModelMapper();
            mapper.AddMappings(Assembly.GetAssembly(typeof(NHibernateHelper)).GetExportedTypes());
            nhCfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            nhCfg.SetProperty("current_session_context_class", "web");

            SessionFactory = nhCfg.BuildSessionFactory();
        }

        public static ISession CurrentSession
        {
            get
            {
                var context = HttpContext.Current;
                var currentSession = context.Items[CurrentSessionKey] as ISession;

                if (currentSession == null && SessionFactory != null)
                {
                    currentSession = GetCurrentSessionInNHibernateContext();
                    context.Items[CurrentSessionKey] = currentSession;
                }

                return currentSession;
            }
        }

        private static ISession GetCurrentSessionInNHibernateContext()
        {
            if (CurrentSessionContext.HasBind(SessionFactory))
                return SessionFactory.GetCurrentSession();

            var session = SessionFactory.OpenSession();
            CurrentSessionContext.Bind(session);

            return session;
        }

        public static ISessionFactory GetSessionFactory()
        {
            return SessionFactory;
        }

        public static void CloseSession()
        {
            var context = HttpContext.Current;
            var currentSession = context.Items[CurrentSessionKey] as ISession;

            if (currentSession == null)
            {
                // No current session
                return;
            }

            currentSession.Close();
            currentSession.Dispose();
            context.Items.Remove(CurrentSessionKey);
        }
    }
}
